package com.sky.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import springfox.documentation.oas.annotations.EnableOpenApi;

@Configuration
public class NetWorkConfig {
    // 当前跨域请求最大有效时长。这里默认1天
    private static final long MAX_AGE = 24 * 60 * 60;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        // 1.设置访问源地址
        // 允许所有域名进行跨域调用
        corsConfiguration.addAllowedOriginPattern("*");
        // 如果要限制仅为指定域名，可以改为
        // corsConfiguration.addAllowedOrigin("http://localhost:8080");

        // 2.设置访问源请求头
        corsConfiguration.addAllowedHeader("*");

        // 3.设置访问源请求方法
        corsConfiguration.addAllowedMethod("*");

        // 4.允许跨域携带cookie
        corsConfiguration.setAllowCredentials(true);

        // 5.设置预检请求的缓存时间（秒），减少预检请求次数
        corsConfiguration.setMaxAge(MAX_AGE);

        // 6.对接口配置跨域设置
        source.registerCorsConfiguration("/**", corsConfiguration);

        return new CorsFilter(source);
    }
}